package top.hymsk.ecommerce.exception;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import top.hymsk.ecommerce.pojo.response.GeneralResponse;
import top.hymsk.ecommerce.pojo.status.ResponseStatusCode;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 花于陌上开
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpServletResponse response;

    @ExceptionHandler(Exception.class)
    public GeneralResponse exception(Exception e) {
        e.printStackTrace(System.err);
        //获取请求方法和请求路径
        String method = request.getMethod();
        String path = request.getServletPath();
        //请求方法参数
        Object args = request.getParameterMap();
        String methodPara = JSONObject.toJSONString(args);
        //获取相应状态
        int status = response.getStatus();
        //日志记录
        log.error(String.format("[%s](%d) %s : %s", method, status, path, methodPara));
        return GeneralResponse.fail(ResponseStatusCode.UNKNOWN_ERROR);
    }
}